var express = require('express');
var router = express.Router();

const Query = require('../utils/db.js')
const { api_url, verifyToken } = require('../utils/config');
const timestamp = require('time-stamp');


//引入文件操作相关的包

const path = require('path')
const fs = require('fs')
const formidable = require('formidable')
const { v4:uuuid } = require('uuid')



/* GET home page. */
router.get('/', async function (req, res, next) {
    res.send('需要token的接口')
});

// router.get('/demo',function(req,res){
//     console.log( req.headers )
//     res.send('demo---' + req.headers.aaa)
// })




//=================================================================================





//根据视频id获取视频的播放地址

router.get('/video', async (req, res, next) => {

    //先验证token是否有效（判断你是否登录了）
    //    let s =  verifyToken( 'adfasfdlkjsafdsajfdlsafdk' )
    // let token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9eyJ1c2VybmFtZSI6InhpYW9taW5nMyIsIm1pZCI6IjRjMmQ1NDliLWE1MzctNGY0Yy05N2VhLTFjYTk5Y2RhY2Y4MCIsImlhdCI6MTYyMzg0MTI3NSwiZXhwIjoxNjU1Mzc3Mjc1fQ.KPF3fUeTY7BFNsutBQMuH5Vrcb98IIbZG1zEZ2g7Qxg'
    // let token = req.headers.authorization
    // if(  !verifyToken( token ) ){
    //    next({
    //        msg:'请传递token',
    //        status:500
    //    })
    //    return
    // }

    let { id = '' } = req.query
    if (id == '') {
        next({
            msg: '请传递必要参数',
            status: 500
        })
        return
    }
    let sql = `SELECT video_title, CONCAT('${api_url}','/uploads/videos/',video_src) AS video_src FROM e_video WHERE id=${id}`
    let res1 = await Query(sql)
    //这里需要判断res1.result的长度是否大于0，如果不大于则代表传的参数不对
    let data = {
        msg: "OK",
        status: 200,
        result: res1.result[0]
    }
    res.send(data)
})




//====================================================================================





//报名 
router.post('/study', async (req, res, next) => {

    let { cid = '', mid = '' } = req.body

    if (cid == '' || mid == '') {
        next({
            "msg": "请传递必要参数",
            "status": 500
        })
        return
    }

    //判断此用户有无报名此课程
    let sql2 = `SELECT * FROM e_order WHERE cid = '${cid}' AND mid = '${mid}'`
    let res2 = await Query(sql2)
    if (res2.result.length > 0) {
        next({
            "msg": "已经报名此课程",
            "status": 500
        })
        return
    }

    // INSERT INTO e_order ( oid,cid,mid,createdate,status ) VALUES ( 'aa1','71f07c0d-f04f-4cb2-a558-7fbf2586f930','mm1',1622105019682,1 )
    let random6 = (Math.random() + '').substring( 2,8 )
    let oid = timestamp('YYYYMMDDHHmmss') + random6  //年月日时分秒 + 6位随机数
    let createdate = Date.now()
    let sql1 = `INSERT INTO e_order ( oid,cid,mid,createdate,status ) VALUES ( '${oid}','${cid}','${mid}',${createdate},1 )`

    let res1 = await Query(sql1)
    if( res1.result.affectedRows > 0 ){
        res.send({
            "msg": "OK",
            "status": 200
          })
    }
})





//====================================================================================





//获取用户信息
router.post('/user', async (req, res, next) => {

    let { mid = '' } = req.body

    if ( mid == '') {
        next({
            "msg": "不传参数就想查询？？？？",
            "status": 500
        })
        return
    }

    //判断是否有此用户，有，显示信息
    let sql3 = `SELECT id,mid,realname,username,sex,birthdate,city,head_photo_url,createdate FROM e_member WHERE mid = '${mid}'`
    let res3 = await Query(sql3)
    console.log(res3.result.length)
    //如果长度为0，代表没有此用户
    if (res3.result.length == 0) {
        next({
            "msg": "查无此人",
            "status": 500
        })
        return
    }
    let data = {
        msg: "OK",
        status: 200,
        result: res3.result[0]
    }
    res.send(data)
})




//====================================================================================





//获取学习记录
router.post('/orders', async (req, res, next) => {

    let { mid = '' } = req.body

    if ( mid == '') {
        next({
            "msg": "不传参数就想查询？？？？",
            "status": 500
        })
        return
    }

    //判断是否有此学习记录，有，显示信息
    let sql4 = `SELECT oid,createdate,cid FROM e_order WHERE mid = '${mid}'`
    let res4 = await Query(sql4)
    let a = res4.result[0]
    console.log(a)

    let sql5 = `SELECT title,price,subject_name,area_name FROM e_course WHERE cid = '${a.cid}'`
    let res5 = await Query(sql5)
    console.log(res5.result)

  
    let data = {
        msg: "OK",
        status: 200,
        result: res5.result
    }
    res.send(data)
})



//======================================================================================-




//更新头像
router.post('/uploadhead',async (req,res,next)=>{

    let { mid='' }  = req.query
    if( mid == '' ){
        next({
            msg:'请传递正确的用户id',
            status:500
        })
        return
    }
     //创建一个处理文件的实例对象
     const form = formidable({
        uploadDir:path.join( __dirname,'../tempdir' ),//一定是涉及到文件的移动操作，推荐使用绝对地址
    })

    //解析文件数据和普通的数据
    form.parse( req ,async (err,fields,files)=>{
        //重命名文件到uploads下

        //如果未选文件，那么size为0 ，判断后缀名是不是 .jpg、.png 、.gif．．．．
        let sourcePath = files.f.path //源路径
        let newname = uuuid() + path.extname( files.f.name ) //带.点
        let newPath = path.join( __dirname ,'../uploads/head' ,newname) 
        fs.renameSync( sourcePath, newPath)

        let sql = `UPDATE e_member SET head_photo_url='${newname}' WHERE mid='${mid}'`
        let res1 = await Query( sql )
        let data = {
            msg:"OK",
            status:200,
            result:`${api_url}/uploads/head/${newname}`
        }
        res.send(data)
    })
})




//====================================================================================




//更新用户信息
router.post('/user',async (req,res,next)=>{

    let { realname='',sex='',birthdate='',city='',mid='' }  = req.query
    if( realname==''||sex==''||birthdate==''||city==''||mid=='' ){
        next({
            msg:'请传递正确的用户id',
            status:500
        })
        return
    }
     
    //解析文件数据和普通的数据
    form.parse( req ,async (err,fields,files)=>{
        let sql6 = `UPDATE e_member SET realname='${realname}',sex='${sex}',birthdate='${birthdate}',city='${city}',mid='${mid}' WHERE mid='${mid}'`
        let res6 = await Query( sql6 )
        console.log(res6.result)
        let data = {
            msg:"OK",
            status:200,
            result:res6.result
        }
        res.send(data)
    })
})


module.exports = router;
